package com.qdev.apps.core.webwork.validator;

import com.opensymphony.xwork.validator.ValidationException;
import com.opensymphony.xwork.validator.validators.FieldValidatorSupport;

/**
 * Rebuild built-in StringLengthFieldValidator to support multi-bytes string
 * 
 * @author Vanish_Wu
 */
public class StringLengthFieldValidator extends FieldValidatorSupport {
    //~ Instance fields ////////////////////////////////////////////////////////

    private boolean doTrim = true;
    private int maxLength = -1;
    private int minLength = -1;

    //~ Methods ////////////////////////////////////////////////////////////////

    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public void setMinLength(int minLength) {
        this.minLength = minLength;
    }

    public int getMinLength() {
        return minLength;
    }

    public void setTrim(boolean trim) {
        doTrim = trim;
    }

    public boolean getTrim() {
        return doTrim;
    }

    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        String val = (String) getFieldValue(fieldName, object);

        if (val == null) {
            addFieldError(fieldName, object);
        } else {
            if (doTrim) {
                val = val.trim();
            }

            if ((minLength > -1) && (val.getBytes().length < minLength)) {
                addFieldError(fieldName, object);
            } else if ((maxLength > -1) && (val.getBytes().length > maxLength)) {
                addFieldError(fieldName, object);
            }
        }
    }
}
